vyCardFrameRaceInfo = {}
vyCardFrameItemInfo = {}
vyCardFrameSelectItem = 1
vyCardFrameScorllBarID = 0;
vyCardFrameMaxItemCount = 50
vyCardFrameItemListSize = 18
vyCardFrameMonsterRaceID = 99
vyCardFrameFirstTimeOnShow = true
vyCardFrameFilter = "";
vyCardMaxCounter = 0;
vyCardFilterCounter = 0;
vyCardContainer = {};
vyCardZoneFilter = -1;

function vyCardFrame_OnShow(this)
	if( vyCardFrameFirstTimeOnShow == true ) then
		vyCardFrameFirstTimeOnShow = false
		LoadCardInfo();
		vyShowSelectedCard();
		vyCardBookFrameSelectMapButton:SetText(vyCardInfoLocales["nozonefilter"]);
		vyCardBookFrameFilterText:SetText(vyCardInfoLocales["filter"] .. ":");
	end
end

-- don't know why, but CARDBOOKFRAME_OPEN ans CLOSE events are not works...
function vyCardFrame_OnUpdate(arg)
	if ( CardBookFrame:IsVisible()) then
		CardBookFrame:Hide();
		if (vyCardBookFrame:IsVisible()) then
			vyCardBookFrame:Hide();
		else
			vyCardBookFrame:Show();
		end
	end
end

function vyCardFrame_OnEvent(this, event)
	if ( event == "CARDBOOKFRAME_OPEN") then
		ShowUIPanel(this);
	elseif ( event == "CARDBOOKFRAME_CLOSE") then
		HideUIPanel(this);
	elseif ( event == "CARDBOOKFRAME_UPDATE") then
--		if ( this:IsVisible()) then
			LoadCardInfo();
--		end
	end
end

-- override the original onshow function
function OnShow_CardFrame()
end

function vyCardFrame_OnLoad(this)
	this:RegisterEvent("CARDBOOKFRAME_OPEN");
	this:RegisterEvent("CARDBOOKFRAME_CLOSE");
	this:RegisterEvent("CARDBOOKFRAME_UPDATE");
	PanelTemplates_SetNumTabs(vyCardBookFrame, 1);
	LuaFunc_InitCardInfo();

	vyCardBookFrameCardImage.angleX = 0;
	vyCardBookFrameCardImage.angleY = 0;

	vyCardBookFrameCardImage.cameraPosX = 0;
	vyCardBookFrameCardImage.cameraPosY = 0;
	vyCardBookFrameCardImage.cameraPosZ = -1;
end

-- dropdown menu for card cats / onload
function vyCardBookFrameTypeDropDown_OnLoad(this)
	UIDropDownMenu_SetWidth(this, 70);
	UIDropDownMenu_Initialize(this, vyCardBookFrameTypeDropDown_Show);
	UIDropDownMenu_SetSelectedID(this, 1);
end

-- dropdown menu for card cats / onshow
function vyCardBookFrameTypeDropDown_Show()
	local info;
	info = {};
	info.text = "All cards";
	info.func = vyCardBookFrameTypeDropDown_Click;
	info.arg1 = 99;
	UIDropDownMenu_AddButton(info);
	for i = 0, 15 do
		if (LuaFunc_GetCardMaxCount(i) > 0) then
			local info;
			info = {};
			info.text = LuaFunc_GetString("SYS_RACE_" .. i)
			info.func = vyCardBookFrameTypeDropDown_Click;
			info.arg1 = i;
			UIDropDownMenu_AddButton(info);
		end
	end
end

-- dropdown menu for card cats / onclick
function vyCardBookFrameTypeDropDown_Click(button)
	UIDropDownMenu_SetSelectedID(vyCardBookFrameType, button:GetID());
	vyCardFrameMonsterRaceID =  button.arg1;
	vyCardFrameSelectItem = 1;
	LoadCardInfo();
	vyShowSelectedCard();
end

-- click on cards name in list
function vyCardFarmeSelectItem_OnClick(this, id , key)
	vyCardFrameSelectItem = id + vyCardFrameScorllBarID ;
	vyShowSelectedCard();

	if( key == "RBUTTON")then
		local T = vyCardFrameItemInfo[vyCardFrameSelectItem];
		if T.CardFlag == 1 then
			ToggleDropDownMenu(vyCardFrameItemMenu, 1, nil, this:GetName());
		end
	end
end

-- show the selected card
function vyShowSelectedCard()
	local ItemHightlight;
	local name;
	local hexid;

	for i = 1 , vyCardFrameItemListSize do
		ItemHightlight = getglobal("vyCardBookFrameList" .. i .. "_Select");
		ItemHightlight:Hide();
	end

	ItemHightlight=  getglobal( "vyCardBookFrameList".. vyCardFrameSelectItem - vyCardFrameScorllBarID .."_Select");
	if ItemHightlight ~= nil then
		ItemHightlight:Show();
	end

	local T = vyCardFrameItemInfo[vyCardFrameSelectItem];
	if (not T) then
		return false;
	end

	hexid = dec2hex(T.CardID);
	local Racetext = LuaFunc_GetString("SYS_RACE_" .. T.CardRace)
	local Raretext = LuaFunc_GetString("SYS_RARECOLOR_" .. T.CardRare)
	if (T.Have == false) then
		vyCardBookFrameCardStatus:SetText("|cffff0000" .. vyCardInfoLocales["donthave"] .. "|r");
		T.CardResist = 0;
	else
		vyCardBookFrameCardStatus:SetText("");
	end
	local location = vyCardInfoLocales["unknown"];
	if (vyCardInfoMobDataFix[T.CardID]) then
		location = GetZoneLocalName(vyCardInfoMobDataFix[T.CardID]);
	elseif (vyCardInfoMobData[T.CardID]) then
		location = GetZoneLocalName(vyCardInfoMobData[T.CardID]);
	end
--	location = location .. " (ID: " .. T.CardID .. ")";
	vyCardBookFrameMobLocation:SetText(vyCardInfoLocales["location"] .. ": " .. location);
	name = "|cff" .. T.OrigColor .. T.CardName .. "|r";
	vyCardBookFrameCardType:SetText(Racetext)
	vyCardBookFrameCardName:SetText(name);
	vyCardBookFrameCardRare:SetText(Raretext);
	vyCardBookFrameCardTip:SetText(T.CardTip);
	vyCardBookFrameCard2DImage:SetTexture("interface\\CardFrame\\CardBk" .. T.CardResist);
	vyCardBookFrameCardImage:SetItemLink("|Hitem:" .. hexid .. "|h|h");
	CloseDropDownMenus();
end

-- filter onkeypress
function vyUpdateCardFilter()
    vyCardFrameFilter = string.lower(vyCardBookFrameFilterBox:GetText());
	vySetCardFilter();
	vyCardFarmeItemListReset();
end

-- using filter...
function vySetCardFilter()
	vyCardFrameItemInfo = {}
	vyCardFilterCounter = 0;
	local vyCardFilterH = 0;
--	local newzone = false;
--	vyCardInfoMobData = {};

	for i = 0, 2 do
		if (vyCardContainer[(2 - i)]) then
			for _, card in pairs(vyCardContainer[(2 - i)]) do
--[[				
				-- mobs' zones
				local ZoneFound;
				if (vyMobAreas["manual"][hexid] == nil and vyMobAreas["npcsearch"][hexid] == nil) then
					local NPCSearchFound = NpcTrack_SearchNpc(card.CardName);
					ZoneFound = 0;
					for i = 1, NPCSearchFound do
						ZoneFound = 0;
						local ZoneID = 0;
						local npcid, npcname, npczone = NpcTrack_GetNpc(i);
						if (npcname == card.CardName) then
							ZoneFound = ZoneFound + 1;
							ZoneID = npczone;
						end
						if (ZoneFound == 1) then
							vyMobAreas["npcsearch"][hexid] = ZoneID;
						end
						newzone = true;
					end
					if (ZoneFound == 0) then
						vyMobAreas["npcsearch"][hexid] = -2;
						newzone = true;
					end
				end

				if (vyMobAreas["npcsearch"][hexid] < 0 and MMODBData[card.CardName] and MMODBData[card.CardName] > 0) then
					vyMobAreas["npcsearch"][hexid] = MMODBData[card.CardName];
					newzone = true;
				end

				if (vyMobAreas["npcsearch"][hexid] and vyMobAreas["npcsearch"][hexid] > 0) then
					vyCardInfoMobData[card.CardID] = vyMobAreas["npcsearch"][hexid];
					DEFAULT_CHAT_FRAME:AddMessage("ok1: " .. card.CardID);
				end
				if (vyMobAreas["manual"][hexid] and vyMobAreas["manual"][hexid] > 0) then
					vyCardInfoMobData[card.CardID] = vyMobAreas["manual"][hexid];
					DEFAULT_CHAT_FRAME:AddMessage("ok2: " .. card.CardID);
				end
]]
				if (vyCardFrameFilter == "" or string.find(string.lower(card.CardName), vyCardFrameFilter)) then
					local zfilter = false;

					if (vyCardZoneFilter == -1) then
						-- no zone filter
						zfilter = true;
					elseif (vyCardZoneFilter == -2 and not vyCardInfoMobDataFix[card.CardID] and not vyCardInfoMobData[card.CardID])  then
						-- unknown mobs
						zfilter = true;
					elseif (vyCardInfoMobDataFix[card.CardID] == vyCardZoneFilter) then
						-- selected area, manual data
						zfilter = true;
					elseif (vyCardInfoMobDataFix[card.CardID] == nil and vyCardInfoMobData[card.CardID] == vyCardZoneFilter) then
						-- selected area, npcsearch data
						zfilter = true;
					end

					if (zfilter == true) then
						vyCardFilterCounter = vyCardFilterCounter + 1;
						vyCardFrameItemInfo[vyCardFilterCounter] = card;
						if (card.Have == true) then
							vyCardFilterH = vyCardFilterH + 1;
						end
					end
				end
			end
		end
	end
--	if (newzone == true) then
--		SaveVariables("vyMobAreas");
--	end
--	SaveVariables("vyCardInfoMobData");

	if (vyCardFrameFilter == "" and vyCardZoneFilter == -1) then
		vyCardBookFrameFilterCountText:Hide();
	else
		vyCardBookFrameFilterCountText:Show();
		vyCardBookFrameFilterCountText:SetText(vyCardInfoLocales["found"] .. ": " .. vyCardFilterH .. "/" .. vyCardFilterCounter);
	end
end

-- cardlist update
function vyCardFarmeItemListReset()
	if (vyCardFrameItemListSize > vyCardFilterCounter) then
		vyCardFrameScorllBarID = 0;
		vyCardBookFrameScrollBar:Hide();
	else
		vyCardBookFrameScrollBar:Show();
		vyCardBookFrameScrollBar:SetMinMaxValues(0, vyCardFilterCounter - vyCardFrameItemListSize);
		vyCardFrameScorllBarID = vyCardBookFrameScrollBar:GetValue();
	end

	for i = 1, vyCardFrameItemListSize do
		local Item = getglobal("vyCardBookFrameList" .. i);
		local ItemHightlight = getglobal("vyCardBookFrameList" .. i .. "_Select");
		local ItemText = getglobal("vyCardBookFrameList" .. i .. "Text");

		if(i <= vyCardFilterCounter) then
				Item:Show();
				ItemHightlight:Hide();
				if (vyCardFrameItemInfo[i + vyCardFrameScorllBarID]) then
					local CardName = vyCardFrameItemInfo[i + vyCardFrameScorllBarID].CardName;
					ItemText:SetText("|cff" .. vyCardFrameItemInfo[i + vyCardFrameScorllBarID].Color .. CardName .. "|r");
				else
					Item:Hide();
				end
		else
			Item:Hide();
		end
	end

	local ItemHightlight=  getglobal("vyCardBookFrameList".. vyCardFrameSelectItem - vyCardFrameScorllBarID .."_Select");
	if ItemHightlight ~= nil then
		ItemHightlight:Show();
	end
	vyShowSelectedCard();
end

-- load card info into vyCardContainer table
function LoadCardInfo()
	vyCardMaxCounter = 0;
	vyCardContainer = {}
	local vyCardCount = 0;

	if (vyCardFrameMonsterRaceID ~= 99) then
		LoadCardInfoRace(vyCardFrameMonsterRaceID);
		vyCardCount = LuaFunc_GetCardCount(vyCardFrameMonsterRaceID);
	else
		vyCardCount = 0;
		for i = 0 , 15 do
			if( LuaFunc_GetCardMaxCount(i) > 0 ) then
				LoadCardInfoRace(i);
				vyCardCount = vyCardCount + LuaFunc_GetCardCount(i);
			end
		end
	end
	vyCardBookFrameCountText:SetText(string.format("(%d/%d)", vyCardCount, vyCardMaxCounter));

	vySetCardFilter();
	vyCardFarmeItemListReset();
end

-- used by the LoadCardInfo
function LoadCardInfoRace(race)
	local vyCardFrameMaxItemCount = LuaFunc_GetCardMaxCount(race);
	for i = 1 , vyCardFrameMaxItemCount do
		local T = {};
		local CardID,CardFlag,CardName,CardTip,CardRace,CardRare,CardResist = LuaFunc_GetCardInfo(race, i - 1)
		T.CardID = CardID;
		T.CardFlag = CardFlag;
		local Cdata = vyCardInfo_GetCardName(dec2hex(T.CardID));
		T.CardName = Cdata["name"];
		T.OrigColor = Cdata["color"];
		if (string.sub(CardName, 1, 1) == "?") then
			T.Have = false;
			T.Color = "777777";
		else
			T.Have = true;
			T.Color = Cdata["color"];
		end
		T.CardTip = CardTip;
		T.CardRace = CardRace;
		T.CardRare = CardRare;
		T.CardResist = CardResist;
		if (not vyCardContainer[CardRare]) then
			vyCardContainer[CardRare] = {};
		end
		if (Cdata["name"] ~= "") then
			vyCardMaxCounter = vyCardMaxCounter + 1;
			table.insert(vyCardContainer[CardRare], T);
		end
	end
end

-- cardlist onmousewheel
function OnMouseWheel_CardFarmeScorllItem(this, delta)
	if ( delta > 0 ) then
		UIPanelScrollBarTemplate_Scroll( vyCardBookFrameScrollBar , "UP");
	else
		UIPanelScrollBarTemplate_Scroll( vyCardBookFrameScrollBar, "DOWN");
	end
end

-- card menu onload
function vyCardFrameItemMenu_OnLoad(this)
	UIDropDownMenu_Initialize(this, vyCardFrameItemMenu_Show, "MENU");
end

-- show card menu on right click
function vyCardFrameItemMenu_Show(this)
	local info = {};
	if (UIDROPDOWNMENU_MENU_LEVEL == 1) then
		info = {};
		info.text = CARDBOOK_TAKEOUTCARD;
		info.notCheckable = 1;
		info.func =
			function()
				local T = vyCardFrameItemInfo[vyCardFrameSelectItem];
				LuaFunc_TakeOutCard(T.CardID);
			end
		info.value = 1;
		UIDropDownMenu_AddButton(info, 1);

		info = {};
		info.text = vyCardInfoLocales["linkcard"];
		info.notCheckable = 1;
		info.func =
			function()
				local T = vyCardFrameItemInfo[vyCardFrameSelectItem];
				local item = "|Hitem:" .. dec2hex(T.CardID) .. "|h|cff" .. T.Color .. "[" .. vyCardInfoLocales["card"] .. " -" .. T.CardName .. "]|r|h";
				ChatEdit_AddItemLink(item);
			end
		info.value	= 2;
		UIDropDownMenu_AddButton(info, 1);

		info = {};
		info.text = C_CANCEL;
		info.notCheckable = 1;
		info.func = function() end;
		info.value = 6;
		UIDropDownMenu_AddButton(info, 1);
	end
end


function vyCardFrameMapSelectMenu_OnLoad(this)
	UIDropDownMenu_Initialize( this, vyCardFrameMapSelectMenu_OnShow, "MENU");
end

function vyCardFrameMapSelectMenu_OnShow(this)

	local info = {};
	if( UIDROPDOWNMENU_MENU_LEVEL == 1 ) then
		info = {};
		info.text 	= vyCardInfoLocales["nozonefilter"];
		info.value	= -1;
		info.func 	=
			function()
				vyCardZoneFilter = -1;
				vyCardBookFrameSelectMapButton:SetText(vyCardInfoLocales["nozonefilter"]);
				vySetCardFilter();
				vyCardFarmeItemListReset();
			end;
		info.owner	= DropDownframe;
		UIDropDownMenu_AddButton( info, 1 );

		info = {};
		info.text 	= vyCardInfoLocales["unknownzone"];
		info.value	= -2;
		info.func 	=
			function()
				vyCardZoneFilter = -2;
				vyCardBookFrameSelectMapButton:SetText(vyCardInfoLocales["unknownzone"]);
				vySetCardFilter();
				vyCardFarmeItemListReset();
			end;
		info.owner	= DropDownframe;
		UIDropDownMenu_AddButton( info, 1 );

		local mapTypeIndex,mapType;

		local typeName;
		for mapTypeIndex,mapType in ipairs( g_MapTypes ) do
			if (mapType == "zone" or mapType == "instance" or mapType == "worldinstance") then
				typeName = string.upper( "UI_WORLDMAP_" .. mapType );
				typeName = TEXT( typeName );
				info = {};
				info.text 	= typeName;
				info.owner	= DropDownframe;
				info.hasArrow	= 1;
				info.value	= mapType;
				UIDropDownMenu_AddButton( info, 1 );
			end
		end

		info = {};
		info.text 	= C_CANCEL;
		info.value	= -99;
		info.func 	= function() end;
		info.owner	= DropDownframe;
		UIDropDownMenu_AddButton( info, 1 );
	elseif( UIDROPDOWNMENU_MENU_LEVEL == 2 ) then
		local continentID = 1;
		local zonesTable;
		local zoneInfo;
		local wp = true;
		local ei = true;
		mapType = UIDROPDOWNMENU_MENU_VALUE;
		zonesTable = WorldMapTable[ continentID ].mapTables[ mapType ];
		for i, val in pairs(zonesTable) do
			local found = false;
			for _, aid in pairs(vyCardInfoMobDataFix) do
				if aid == val.id then
					found = true;
				end
			end

			if (found == false) then
				for _, aid in pairs(vyCardInfoMobData) do
					if aid == val.id then
						found = true;
					end
				end
			end

			-- guards' corridor has an instance name too (cavern of trials)
			if (maptype == "instance" and val.id == 206) then found = false; end;
			-- fix, show elven island even if those aren't in the list
			if (val.id == 12) then ei = false; end;

			if (found == true) then
				info = {};
				info.text 	= val.name;
				info.value	= val.id;
				info.func =
					function()
						vyCardBookFrameSelectMapButton:SetText(val.name);
						vyCardZoneFilter = val.id;
						vySetCardFilter();
						vyCardFarmeItemListReset();
					end
				UIDropDownMenu_AddButton( info, 2 );
			end
		end
		
		if (mapType == "zone" and ei == true) then
			info = {};
			info.text = GetZoneLocalName(12);
			info.value	= 12;
			info.func =
				function()
					vyCardBookFrameSelectMapButton:SetText(GetZoneLocalName(12));
					vyCardZoneFilter = 12;
					vySetCardFilter();
					vyCardFarmeItemListReset();
				end
			UIDropDownMenu_AddButton( info, 2 );
		end
	end

end